package com.infinitus.activity.util;

import com.infinitus.activity.pojo.VO.AddPointsVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;

/**
 * @create: 2019/1/9
 * @desc: 纷享会接口
 */
@Component
public class FxhClient {

    private Logger log = LoggerFactory.getLogger(FxhClient.class);

    @Value("${fxh.siebelUrl}")
    private String url;
    @Value("${fxh.siedbeUsername}")
    private String userName;
    @Value("${fxh.siedbePassword}")
    private String password;

    public String addPoints(AddPointsVO vo) {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

        String xml = "<x:Envelope xmlns:x=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:inf=\"http://siebel.com/xml/INFIPointContral\" xmlns:web=\"http://siebel.com/webservices\" >\n" +
                "    <x:Header>\n" +
                "        <web:SessionType>None</web:SessionType>\n" +
                "        <web:SessionToken/>\n" +
                "        <web:UsernameToken>" + this.userName + "</web:UsernameToken>\n" +
                "        <web:PasswordText>" + this.password + "</web:PasswordText>\n" +
                "    </x:Header>\n" +
                "    <x:Body>\n" +
                "        <inf:AddPoints>\n" +
                "            <pointValue>" + vo.getPointValue() + "</pointValue>\n" +
                "            <remark>" + vo.getRemark() + "</remark>\n" +
                "            <activte_type>" + vo.getActiveType() + "</activte_type>\n" +
                "            <interactivate_date>" + sdf.format(vo.getInteractivateDate()) + "</interactivate_date>\n" +
                "            <source_system>" + vo.getSourceSystem() + "</source_system>\n" +
                "            <cardNo>" + vo.getCardNo() + "</cardNo>\n" +
                "            <integral_type>" + vo.getIntegralType() + "</integral_type>\n" +
                "        </inf:AddPoints>\n" +
                "    </x:Body>\n" +
                "</x:Envelope>";
        return post(xml);
    }

    private String post(String xml) {
        CloseableHttpResponse response = null;
        try (CloseableHttpClient httpclient = HttpClients.createDefault()) {

            try {
                HttpPost request = null;
                request = new HttpPost();
                request.setHeader("Accept-Encoding", "gzip");
                request.setHeader("content-type", "text/xml;charset=UTF-8");

                request.setHeader("SOAPAction", "<soap:operation soapAction=\"rpc/http://siebel.com.xml/INFIFXHPointsExchangeNew:NewIntegralChange\"/>");

                log.info("send xml: " + xml);

                request.setEntity(new StringEntity(xml, "UTF-8"));


                 URL url = new URL(this.url);
                 URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
                request.setURI(uri);
                log.debug("executing request " + request.getURI());

                response = httpclient.execute(request);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String content = EntityUtils.toString(entity, "UTF-8");
                    log.debug("--------------------------------------");
                    log.info("Response content: " + content);
                    log.debug("--------------------------------------");

                    Document doc = Jsoup.parse(content);
                    Elements procCodes = doc.select("procCode");

                    String porcCode = procCodes.html();
                    if (!StringUtils.equals(porcCode, "1")) {
                        log.info(content);
                    }

                    return porcCode;
                }
            } catch (Exception e1) {
                log.error(e1.getMessage(), e1);
            }
        } catch (IOException e1) {
            log.error(e1.getMessage(), e1);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e1) {
                    log.error(e1.getMessage(), e1);
                }
            }
        }

        return null;
    }


    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}